import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/index',
      redirect: '/botnav/index'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/msg',
      name: 'msg',
      component: () => import('@/views/Msg.vue')
    },
    {
      path: '/botnav',
      name: 'botnav',
      component: () => import('@/views/Botnav.vue'),
      children: [
        {
          path: 'index',
          name: 'index',
          component: () => import('@/views/Index.vue'),
          meta: {
            requireAuth: true
          }
        },
        {
          path: 'plan',
          name: 'plan',
          component: () => import('@/views/Plan.vue'),
          meta: {
            requireAuth: true
          }
        },
        {
          path: 'mine',
          name: 'mine',
          component: () => import('@/views/Mine.vue'),
          meta: {
            requireAuth: true
          }
        }
      ]
    },
    {
      path: '/course',
      name: 'course',
      component: () => import('@/views/Course.vue'),
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/coursemore',
      name: 'coursemore',
      component: () => import('@/views/CourseMore.vue'),
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/personalinfo',
      name: 'personalinfo',
      component: () => import('@/views/PersonalInfo.vue'),
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/progress',
      name: 'progress',
      component: () => import('@/views/StudyProgress.vue'),
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/notices',
      name: 'notices',
      component: () => import('@/views/Notices.vue'),
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/noticeinfo',
      name: 'noticeinfo',
      component: () => import('@/views/NoticeInfo.vue'),
      meta: {
        requireAuth: true
      }
    }
  ],
  lastPathName: ''
});

export default router

router.beforeEach((to, from, next) => {
  router.lastPathName = from.name;
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    let currentUser = JSON.parse(localStorage.getItem("currentUser"));
    if (!currentUser) currentUser = {};
    let token = currentUser.token;
    if (token && token.length > 0) { // 判断本地是否存在token
      next()
    } else {
      // 未登录,跳转到登陆页面
      next({
        path: '/login'
      })
    }
  } else {
    next();
  }
});
